package com.emm.yixun.website.controller.system;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.emm.yixun.common.excel.FastExcel;
import com.emm.yixun.common.exception.BusinessException;
import com.emm.yixun.common.model.Company;
import com.emm.yixun.common.model.Department;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CompanyDto;
import com.emm.yixun.common.model.dto.DepartmentDto;
import com.emm.yixun.common.model.dto.DepartmentModel;
import com.emm.yixun.common.model.dto.MarketingModel;
import com.emm.yixun.common.model.dto.MarketingModel_CW;
import com.emm.yixun.common.model.dto.UserModel;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.system.service.CompanyServiceFacade;
import com.emm.yixun.system.service.DepartmentServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.common.utils.tree.entity.ZNodes;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.entity.system.org.Position;
import com.emm.yixun.website.vo.CustomerImportVo;

import net.sf.json.JSONArray;
/*
 * 机构管理
 */
@Controller
@RequestMapping("/backstage/org/position/")
public class PositionController extends BaseController<Position>{
	
	@Autowired
	private DepartmentServiceFacade departmentServiceFacade;
	@Autowired
	private CompanyServiceFacade companyServiceFacade;
	
	private static final String SECURITY_URL="/backstage/org/position/index";
	/**
	 * 职务管理首页
	 */
	@RequestMapping("index")
	public String index(Model model, HttpServletRequest request) {	
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			List<com.emm.yixun.common.model.Resources> resources=getPermitBtn(Const.RESOURCES_TYPE_FUNCTION);
			model.addAttribute("permitBtn", resources);		
			model.addAttribute("btnListJson", JSONArray.fromObject(resources));
			model.addAttribute("menu", request.getParameter("menu"));
			return "/system/org/position/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	@RequestMapping(value="getOrgAndPositionTree", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes getOrgAndPositionTree(DepartmentDto departmentDto){
		AjaxRes ar=getAjaxRes();
		if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU,SECURITY_URL))){	
			try {
				
				ar.setSucceed(getZnodeInfo(departmentDto, ar));
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}
	
	public List<ZNodes> getZnodeInfo(DepartmentDto departmentDto,AjaxRes ar){
	    	List<ZNodes> r=new ArrayList<ZNodes>();
	    	User user=ShiroUtil.getCurrentUser();
		departmentDto.setMerchantId(user.getMerchantId());
		departmentDto.setPermissionUserId(user.getId());
		
		//机构数据权限资源缓存
		String resourcesCode = ShiroUtil.getDataPermissionResources(departmentDto.getResourcesName());
		if(null == departmentDto.getResourcesCode() || "".equals(departmentDto.getResourcesCode())){
			departmentDto.setResourcesCode(resourcesCode);
		}else if("".equals(resourcesCode)){
			ShiroUtil.setDataPermissionResources(departmentDto.getResourcesName(), departmentDto.getResourcesCode());
		}
		departmentDto.setOrders("sort asc");
		ResponseList<Department> responseList=departmentServiceFacade.findByDto(departmentDto);
		if(!responseList.isSuccess()){
			ar.setFailMsg(Const.DATA_FAIL);
			if(StringUtils.isNotEmpty(responseList.getResultMessage())){
				ar.setFailMsg(responseList.getResultMessage());
			}
		}
		if(null==responseList.getEntity()){
			responseList.setEntity(new ArrayList<Department>());
		}
		List<String> companyCodeList = new ArrayList<String>();
		//组装Znodes
		for(Department dt : responseList.getEntity()){
			ZNodes znode=new ZNodes();
			znode.setId(String.valueOf(dt.getId()));
			if(dt.getParentId().compareTo(-1L)==0){
				if(StringUtils.isNotEmpty(dt.getSubcompanyCode())){
					Company company = getCompanyByCode(dt.getSubcompanyCode());
					if(null != company){
						znode.setpId(company.getId().toString());
					    companyCodeList.add(dt.getSubcompanyCode());
					}
				}
			}else{
			    znode.setpId(dt.getParentId().toString());
			}
			znode.setName(dt.getDepartmentName());
			znode.setOther("o");
			r.add(znode);
		}
		
		//去除重复值
		HashSet<String> hashSet = new HashSet<String>(companyCodeList);
		if(hashSet!=null&&hashSet.size()>0){
		    for (String code:hashSet) {
		    	if(StringUtils.isNotEmpty(code)){
		    		Company company = getCompanyByCode(code);
				    if(company==null){
				    	continue;
				    }
				    ZNodes node = new ZNodes();
				    node.setId(company.getId().toString());
				    node.setpId("-1");
				    node.setName(company.getSubcompanyName());
				    node.setOther("o");
				    r.add(node);
		    	}
		    }
		}
		return r;
	}
	/**
	 * 根据CODE获取COMPANY信息
	 * @param code
	 * @return
	 */
	public Company getCompanyByCode(String code){
	    CompanyDto companyDto = new CompanyDto();
	    companyDto.setCompanyCode(code);
	    companyDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
	   ResponseList<Company> responseCompanyList = companyServiceFacade.findByDto(companyDto);
	   if(responseCompanyList.isSuccess()&&responseCompanyList.getEntity()!=null&&responseCompanyList.getEntity().size()>0){
	       Company company = responseCompanyList.getEntity().get(0);
	       return company;
	   }
	   return null;
	}
	@RequestMapping(value="getPreOrgTree")
	@ResponseBody
	public AjaxRes getPreOrgTree(DepartmentDto departmentDto){
		AjaxRes ar=getAjaxRes();
		if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_MENU,SECURITY_URL))){	
			try {
			    ar.setSucceed(getZnodeInfo(departmentDto, ar));
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}	
		return ar;
	}
	//新增部门
	@RequestMapping(value="addPos", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes addDepartment(DepartmentDto dt,String orgId){
		AjaxRes ar=getAjaxRes();
		if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:org:add"))){	
			try {
				User user=ShiroUtil.getCurrentUser();
				Long parentId=null;
				if(StringUtils.isNotBlank(orgId)){
					parentId=Long.valueOf(orgId);
				}else{
					parentId=Long.valueOf("-1");
				}
				dt.setParentId(parentId);
				dt.setSort("1");
				dt.setMerchantId(user.getMerchantId());
				dt.setCreateUserId(user.getId());
				dt.setDelFlag("0");
				dt.setUpdateTime(new Date());
				Response<DepartmentDto> response=departmentServiceFacade.save(dt);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
				
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}
	//查询部门
	@RequestMapping(value="findDepartmentById", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes getDepartmentById(Long id){
		AjaxRes ar=getAjaxRes();
		if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:org:view"))){	
			try {
				Response<Department> response=departmentServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());;
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}
	
	@RequestMapping(value="updateDepartment", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes updateDepartment(DepartmentDto dt){
		AjaxRes ar=getAjaxRes();	
		if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:org:edit"))){	
				try {
					 dt.setUpdateTime(new Date());
					 if(null != dt.getOrgId()){
						dt.setParentId(dt.getOrgId());
					 }
					 Response<Integer> response = departmentServiceFacade.updateByPrimaryKey(dt, true);
					 if(response.isSuccess()){
//						 ar.setSucceedMsg(Const.UPDATE_SUCCEED);
						 ar.setSucceedMsg(Const.SAVE_SUCCEED);
					 }else{
						 ar.setFailMsg(Const.UPDATE_FAIL);
					 }
				} catch (Exception e) {
					logger.error(e.toString(),e);
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			 
		}	
		return ar;
	}
	
	@RequestMapping(value="delDepartment", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes delDepartment(Long id){
		AjaxRes ar=getAjaxRes();
		if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:org:delete"))){	
			try {
				/**
				 * 1.删除当前部门以及子部门
				 * 2.删除部门所有员工
				 */
				Response<Boolean> response=departmentServiceFacade.deleteByParentId(id);
				if(response.isSuccess() && response.getEntity()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else{
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}	
		return ar;
	}
	
	/**
	 * 部门信息导入
	 * @param request
	 * @param multipartFile
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "departmentImport")
	@ResponseBody
	public AjaxRes departmentImport(HttpServletRequest request,
			@RequestParam("multipartFile")MultipartFile multipartFile,HttpServletResponse response) {
		AjaxRes ar = getAjaxRes();
		response.setContentType("text/html; charset=utf-8");
		
		FastExcel fastExcel = null;
		try {
			User user = ShiroUtil.getCurrentUser();
			//解析Excel数据并转为java实体bean
			fastExcel = new FastExcel(multipartFile.getInputStream());
			//获取部门信息标签的数据
			fastExcel.setSheetName("部门信息");
			//从第1行获取（标题为第0行）
			fastExcel.setStartRow(1);
			List<DepartmentModel> list = fastExcel.parse(DepartmentModel.class);
			//导入部门信息
			Response<String> res = departmentServiceFacade.departmentImport(list, user);
			if(res.isSuccess()) {
				ar.setSucceed(res.getEntity());
			}
		} catch (BusinessException e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(e.getErrorMsg());
		} catch (Exception e) {
			logger.error("部门信息导入失败", e);
			ar.setFailMsg(e.getMessage());
		} finally {
			try {
				fastExcel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ar;
	}
	
	/**
	 * 用户信息导入
	 * @param request
	 * @param multipartFile
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "userInfoImport")
	@ResponseBody
	public AjaxRes userInfoImport(HttpServletRequest request,
			@RequestParam("userInfoFile")MultipartFile multipartFile,HttpServletResponse response) {
		AjaxRes ar = getAjaxRes();
		response.setContentType("text/html; charset=utf-8");
		FastExcel fastExcel = null;
		try {
			User user = ShiroUtil.getCurrentUser();
			//解析Excel数据并转为java实体bean
			fastExcel = new FastExcel(multipartFile.getInputStream());
			//获取在职员工标签的数据
			fastExcel.setSheetName("在职员工");
			//从第1行获取（标题为第0行）
			fastExcel.setStartRow(1);
			List<UserModel> list = fastExcel.parse(UserModel.class);
			//导入用户信息
			Response<String> res = departmentServiceFacade.userInfoImport(list, user.getMerchantId());
			if(res.isSuccess()) {
				ar.setSucceed(res.getEntity());
			}
		} catch (BusinessException e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(e.getErrorMsg());
		} catch (Exception e) {
			logger.error("用户信息导入失败", e);
			ar.setFailMsg(e.getMessage());
		} finally {
			try {
				fastExcel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ar;
	}
}
